package com.beiding.dbrequest.common;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.apache.dubbo.common.serialize.hessian2.Hessian2ObjectOutput;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @author 丁常磊
 * @date 2021/7/16 9:19
 */

public class HessianEncoder extends MessageToMessageEncoder<Message> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, List<Object> list) throws Exception {
        ByteBuf directBuf = Unpooled.directBuffer();
        Hessian2ObjectOutput hessian2ObjectOutput = new Hessian2ObjectOutput(new OutputStream() {
            @Override
            public void write(int b) throws IOException {//不会调用没有意义
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                directBuf.writeBytes(b, off, len);
            }
        });
        hessian2ObjectOutput.writeObject(message);
        //需要刷入数据
        hessian2ObjectOutput.flushBuffer();
        list.add(directBuf);
    }
}
